﻿using BootstrapBlazor.Components;
using CyssBlazor.Shared.Components;
using CyssBlazor.Shared.Infrastructure;
using CyssBlazor.Shared.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Pages.Commons
{
    public partial class LoginPage 
    {

        private Button loginButton;

        [Inject]
        private IUserAuthenService userAuthenService { set; get; }

        [Inject]
        private NavigationManager navigationManager { set; get; }


        private LoginViewModel loginModel { set; get; } = new LoginViewModel();

        protected async override Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await _jSRuntime.InvokeVoidAsync("$.login_set_page", DotNetObjectReference.Create(this));
                loginModel.UserNo = await _userAuthenService.GetLoginUserName();
                loginModel.UserPwd = "";
                loginModel.UserNo = loginModel.UserNo.Replace("\"", "");
                await InvokeAsync(StateHasChanged);
            }
        }

        [JSInvokable]
        public async Task Keydowns(int KeyCode)
        {
            if (KeyCode==13)
            {
                await loginButton.SimulatedClick(_jSRuntime);
            }
        }


        public async Task LoginSubmit()
        {
            loginModel.Message = string.Empty;
            await InvokeAsync(StateHasChanged);
            if (string.IsNullOrWhiteSpace(loginModel.UserNo) || string.IsNullOrWhiteSpace(loginModel.UserPwd))
            {
                loginModel.Message = "请输入用户名和密码";
                return;
            }
            var isSuccess = await userAuthenService.LoginAsync(loginModel);

            if (isSuccess)
            {
                loginModel.Message = "成功";
                navigationManager.NavigateTo("/index");
            }
            else
            {
                loginModel.Message = "登录失败！请检查用户名和密码是否输入正确";

            }
            await InvokeAsync(StateHasChanged);

        }




    }
}
